<template>
  <div class="canvas1">
    <canvas id="can3" width="750" height="1624"></canvas>
    <img :src="imgTu" alt="" />
  </div>
</template>
<script>
  import bgMapMgr from '@/biz/bgMap/bgMap'
  import { resolveTripleslashReference } from 'typescript'
  export default {
    // props: ["tuUrl1", "editorInfo", "shortDetails", "keyIndex"],
    components: {},
    data() {
      return {
        buildMess: this.$dt.buildInfo(), //案场的所有信息
        houseName: '这里显示楼盘名称',
        articleTitle: '这是个标题样例，至多20个字。这是个标题样例',
        articleCon:
          '这是正文内容样例，至多150个字。这是正文内容样例，至多150个字。这是正文内容样例，至多150个字。这是正文内容样例，至多150个字。这是正文内容样例，至多150个字。这是正文内容样例，至多150个字。这是正文内容样例，至多150个字。这是正文内容样例，至多150个字。这是正文内容样例，至多150',
        adviserName: '麦房宝',
        adviserTel: '13888888888',
        adviserWX: 'tospur',
        imgTu: '/static/images/template/tu.jpg',
        // imgHouse: "/static/images/template/fang.png",
        imgHeng: '/static/images/template/heng.png',
        canvasId: 'canvas' + this.keyIndex,
        canvasImgUrl: '',
        imgHouse: 'https://images.tospurfang.com/dt/9596421ba90b4c2c9b8c469edf7d73da.png',
        imgxbg: 'https://images.tospurfang.com/dt/0d3a1bf1ae1e4e62bdd1ebf22a677898.png'
      }
    },

    methods: {
      updateBa(val, canvasImgUrl) {
        let params = {
          backgroudUrl: val.backgroudUrl,
          backgroundId: val.backgroundId,
          buildingId: this.$dt.buildInfo().housesId,

          content: val.content,
          picUrl: val.picUrl,
          title: val.articleName,
          templateName: val.templateName,
          dominateScreen: val.dominateScreen,
          saleOffice: val.saleOffice,
          id: val.id,
          // templateImage: JSON.parse(this.$tool.getStorage('canvasImg')),

          templateImage: canvasImgUrl
        }

        bgMapMgr
          .shortSrticleUpdateById(params)
          .then((res) => {
            // return await new Promise((resolve, reject) => {
            //   resolve('11')
            // })
          })
          .catch((err) => {
            this.loading = false
            this.$Message.error(err)
          })
      },
      // 生成图片
      convertCanvasToImage(info, houseAuit) {
        var canvas = document.getElementById('can3')
        var image = new Image()
        image.crossOrigin = ''
        image.src = canvas.toDataURL('image/png')
        this.unloadFileCanvas(image.src, info, houseAuit)
      },
      unloadFileCanvas(image, info, houseAuit) {
        let params = {}
        params.multipartFile = this.base64toFile(image)
        params.title = info.title
        bgMapMgr.unloadFileCanvas(params).then((res) => {
          this.canvasImgUrl = res.imageURL
          console.log('生成图片')
          this.$store.dispatch('canvasImg', this.canvasImgUrl)
          if (houseAuit) {
            if (res && res.imageURL) {
              this.updateBa(info, res.imageURL)
            }
          }
        })
      },
      base64toFile(base, filename) {
        var arr = base.split(',')
        var mime = arr[0].match(/:(.*?);/)[1]
        var suffix = mime.split('/')[1]
        var bstr = atob(arr[1])
        var n = bstr.length
        var u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        //转换成file对象
        return new File([u8arr], `${filename}.${suffix}`, { type: mime })
      },

      fillRoundRect(cxt, x, y, width, height, radius, fillColor, direction) {
        //圆的直径必然要小于矩形的宽高
        if (2 * radius > width || 2 * radius > height) {
          return false
        }

        cxt.save()
        cxt.translate(x, y)
        //绘制圆角矩形的各个边
        this.drawRoundRectPath(cxt, width, height, radius, direction)
        cxt.fillStyle = fillColor || '#000' //若是给定了值就用给定的值否则给予默认值
        cxt.fill()
        cxt.restore()
      },
      // strokeRoundRect(cxt, x, y, width, height, radius, /*optional*/ lineWidth, /*optional*/ strokeColor) {
      //   //圆的直径必然要小于矩形的宽高
      //   if(2 * radius > width || 2 * radius > height) {
      //     return false;
      //   }

      //   cxt.save();
      //   cxt.translate(x, y);
      //   //绘制圆角矩形的各个边
      //   this.drawRoundRectPath(cxt, width, height, radius);
      //   cxt.lineWidth = lineWidth || 2; //若是给定了值就用给定的值否则给予默认值2
      //   cxt.strokeStyle = strokeColor || "#000";
      //   cxt.stroke();
      //   cxt.restore();
      // },
      drawRoundRectPath(cxt, width, height, radius, direction) {
        cxt.beginPath(0)
        //从右下角顺时针绘制，弧度从0到1/2PI
        direction == 'down' && cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2)
        //矩形下边线
        cxt.lineTo(direction == 'up' ? 0 : radius, height)
        //左下角圆弧，弧度从1/2PI到PI
        direction == 'down' && cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI)
        //矩形左边线
        cxt.lineTo(0, direction == 'down' ? 0 : radius)
        //左上角圆弧，弧度从PI到3/2PI
        direction == 'up' && cxt.arc(radius, radius, radius, Math.PI, (Math.PI * 3) / 2)
        //上边线
        cxt.lineTo(direction == 'down' ? width : width - radius, 0)
        //右上角圆弧
        direction == 'up' && cxt.arc(width - radius, radius, radius, (Math.PI * 3) / 2, Math.PI * 2)
        //右边线
        cxt.lineTo(width, direction == 'up' ? height : height - radius)
        cxt.closePath()
      },

      textline(txt, font, width) {
        let txts = txt.split('\n')
        let line = 0
        for (var key in txts) {
          line += Math.ceil(this.getwidth(txts[key], font) / width)
        }
        return line
      },
      // 绘制自动换行的文本
      canvasTextAutoLine(str, ctx, initX, initY, lineHeight, lineNum) {
        let arr = str.split('\n')
        var lineda = 1
        var canvasWidth = '656'

        arr.forEach((item, index) => {
          let lineWidth = 0
          let lastSubStrIndex = 0

          if (index > 0) {
            initY += lineHeight
            lineda += 1
          }
          if (lineNum && lineda > lineNum) {
            return false
          }

          for (let i = 0; i < item.length; i++) {
            lineWidth += ctx.measureText(item[i]).width
            if (lineWidth > canvasWidth - initX) {
              //减去initX,防止边界出现的问题
              if (lineNum && lineda > lineNum) {
                return false
              } else {
                ctx.fillText(item.substring(lastSubStrIndex, i), initX, initY)
                initY += lineHeight
                lineda += 1
                lineWidth = 0
                lastSubStrIndex = i
              }
            }
            if (i == item.length - 1) {
              ctx.fillText(item.substring(lastSubStrIndex, i + 1), initX, initY)
            }
          }
        })
      },

      xianDuan(info, houseAuit) {
        console.log(info, '2222')
        const houseName = info.housesName || this.buildMess.buHousesName //楼盘名字
        const articleTitle = info.articleName //文章名字
        const articleCon = info.content //文章内容
        const _imgTu = info.picUrl || info.fileList[0].url //头图
        const tuUrl1 = info.tuUrl1 //背景图

        var canvas = document.createElement('canvas')
        canvas.height = 1624
        canvas.width = 750
        var ctx = canvas.getContext('2d')

        // 加载背景图片
        ctx.beginPath()
        let img = new Image()
        img.crossOrigin = ''
        img.src = tuUrl1
        img.onload = () => {
          ctx.drawImage(img, 0, 0, 750, 1624, 0, 0, 750, 1624)

          ctx.beginPath()
          let imgxbg = new Image()
          imgxbg.crossOrigin = ''
          imgxbg.src = this.imgxbg
          imgxbg.onload = () => {
            ctx.drawImage(imgxbg, 0, 0, 672, 1223, 39, 135, 672, 1223)
            // icon
            ctx.beginPath()
            let imgHouse = new Image()
            imgHouse.crossOrigin = ''
            imgHouse.src = this.imgHouse
            imgHouse.onload = () => {
              ctx.drawImage(imgHouse, 0, 0, 44, 52, 72, 163, 44, 52)
              // 楼盘名称
              ctx.beginPath()
              ctx.fillStyle = '#9D9EA9'
              ctx.font = '32px arial'
              ctx.fillText(houseName, 128, 206)

              ctx.closePath()
              // ctx.closePath();
              // // 绘制圆角矩形
              // ctx.beginPath()
              // this.fillRoundRect(ctx, 40, 336, 670, 860, 20, 'white', 'down')
              // ctx.closePath()

              // ctx.closePath();
              // 标题
              ctx.beginPath()
              ctx.fillStyle = '#191B2D'
              ctx.font = 'bold 48px arial'
              this.canvasTextAutoLine(articleTitle, ctx, 72, 326, 64)
              ctx.closePath()

              // 原点背景
              // ctx.beginPath()
              // this.fillRoundRect(ctx, 40, 276, 670, 60, 20, 'white', 'up', 'globalAlpha')
              // ctx.closePath()
              // // 两个原点
              // ctx.beginPath()
              // ctx.fillStyle = 'white'
              // ctx.arc(80, 310, 12, 0, Math.PI * 2, false)
              // ctx.fill()
              // ctx.closePath()

              // ctx.beginPath()
              // ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'
              // ctx.arc(96, 310, 12, 0, Math.PI * 2, false)
              // ctx.fill()
              // ctx.closePath()

              // 文本内容
              ctx.beginPath()
              ctx.fillStyle = '#333'
              ctx.font = '30px arial'
              this.canvasTextAutoLine(articleCon, ctx, 72, 952, 46, 8)
              ctx.closePath()
              // 头图片 圆角

              ctx.beginPath()
              let x = 72
              let y = 456
              let width = 606
              let height = 404
              let radius = 20
              ctx.moveTo(x + radius, y)
              ctx.lineTo(x + width - radius, y)
              ctx.quadraticCurveTo(x + width, y, x + width, y + radius)
              ctx.lineTo(x + width, y + height - radius)
              ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height)
              ctx.lineTo(x + radius, y + height)
              ctx.quadraticCurveTo(x, y + height, x, y + height - radius)
              ctx.lineTo(x, y + radius)
              ctx.quadraticCurveTo(x, y, x + radius, y)
              ctx.clip()

              let imgTu = new Image()
              imgTu.crossOrigin = ''
              imgTu.src = _imgTu
              imgTu.onload = () => {
                // ctx.drawImage(imgTu, 72, 760, 606, 402);
                ctx.drawImage(imgTu, 72, 456, 606, 404)

                setTimeout(() => {
                  var image = new Image()
                  image.crossOrigin = ''
                  image.src = canvas.toDataURL('image/png')
                  this.unloadFileCanvas(image.src, info, houseAuit)
                }, 1000)
              }
              ctx.closePath()
            }
          }

          ctx.closePath()
        }
        ctx.closePath()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .canvas1 {
    width: 750px;
    // padding: 0 20px 45px;
    // box-sizing: border-box;
    margin: 0 auto;
    // background-size: 100% 100%;
    height: 1624px;
    position: relative;
    zoom: 0.5;
    // transform-origin: 0% 0%;//设置左上角为原点
    // transform:scale(0.5,0.5);
    // margin-bottom: -50%;
  }

  .allBox {
    padding: 0 40px;
    position: absolute;
    top: 1132px;
    left: 0;
    width: 100%;
    z-index: 99999;
  }

  .box {
    padding: 24px 32px;
  }

  .box1 {
    padding: 24px 32px 24px;
    border-radius: 20px 20px 0 0;
  }

  .tou {
    background: linear-gradient(314deg, #f2e2c8 0%, #f5e9d6 100%);
    display: flex;
    flex-direction: row;
    padding: 24px;
    border-radius: 16px;

    .touImg {
      margin-right: 24px;

      img {
        width: 116px;
        height: 116px;
        border-radius: 50%;
        display: block;
      }
    }

    .touText {
      p.p1 {
        font-size: 36px;
        font-weight: 500px;
        line-height: 36px;
        color: #705f42;
        margin: 20px 0 20px;

        span {
          background: linear-gradient(90deg, #ead3ac 0%, #fce7c3 100%);
          border-radius: 20px;
          font-size: 20px;

          display: inline-block;
          padding: 2px 12px;
        }
      }

      p.p2 {
        img {
          width: 28px;
          height: 26px;
        }

        span {
          font-size: 24px;
          font-weight: 400;
          color: #524838;
          line-height: 28px;
          display: inline-block;
          margin: 0 30px 0 6px;
          vertical-align: 6px;
        }
      }
    }
  }

  .er {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-top: 20px;

    .erText {
      flex: 1;

      p {
        font-size: 36px;
        font-weight: 800;
        color: #333333;
      }

      span {
        display: block;
        font-size: 24px;
        font-weight: 400;
        color: #333333;
        margin-top: 32px;
      }
    }

    .erImg {
      width: 140px;
      height: 140px;
      display: block;
    }
  }
</style>
